import React, { useEffect, useRef, useState } from 'react'
//底部组件
import startAudioImg from '../assets/images/speeching.gif'
import stopAudioImg from '../assets/images/speaking.jpeg'
import { useNavigate } from 'react-router-dom';

function BottomCom() {
  // 语音识别相关的变量
  const recognition = useRef<any | null>(null);
  const [isListening, setIsListening] = useState(false);
  const [flag, setFlag] = useState(true)
  const [isWhite, setIsWhite] = useState(false);
  const navigate=useNavigate()

  // 监听 localStorage 变化（包括当前页面和跨标签页）
  useEffect(() => {
    // 1. 定义更新状态的函数
    const updateTheme = () => {
      setIsWhite(localStorage.getItem('theme') === 'white');
    };

    // 2. 初始化主题状态
    updateTheme();

    // 3. 监听当前页面的自定义事件（手动触发）
    const handleLocalChange = () => updateTheme();
    window.addEventListener('local-storage-change', handleLocalChange);

    // 4. 监听其他标签页的 storage 事件
    window.addEventListener('storage', updateTheme);

    // 清理事件监听
    return () => {
      window.removeEventListener('storage', updateTheme);
      window.removeEventListener('local-storage-change', handleLocalChange);
    };
  }, []);

  // 语音识别初始化
  useEffect(() => {
    // 检查浏览器是否支持语音识别
    if ("webkitSpeechRecognition" in window) {
      recognition.current = new webkitSpeechRecognition();
      recognition.current.continuous = true;
      recognition.current.interimResults = true;
      recognition.current.lang = "zh-CN";

      // 当语音识别结果可用时的回调
      recognition.current.onresult = (event: any) => {
        const transcript =
          event.results[event.resultIndex][0].transcript.trim();
        console.log("识别到的语音:", transcript);

       // 根据识别到的语音内容 作出反应和内容切换动作
       if (transcript.includes("豆包")) {
           navigate('/layout/chat')
           recognition.current.stop();
           setIsListening(false);
           setFlag(true)
        } else if (transcript.includes("进入聊天")) {
           navigate('/layout/chat')
           recognition.current.stop();
           setIsListening(false);
           setFlag(true)
        } else if (transcript.includes("ai")) {
          navigate('/layout/chat')
          recognition.current.stop();
           setIsListening(false);
           setFlag(true)
        } else if (transcript.includes("关闭语音")) {
            recognition.current.stop();
           setIsListening(false);
           setFlag(true)
        }else if (transcript.includes("转圈圈")) {    
          window.dispatchEvent(new CustomEvent('voice-action', { detail: "转圈圈" }));
        } else if (transcript.includes("给我爬")) {
          window.dispatchEvent(new CustomEvent('voice-action', { detail: "给我爬" }));
        } else if (transcript.includes("小跳一下")) {
          window.dispatchEvent(new CustomEvent('voice-action', { detail: "小跳一下" }));
        } else if (transcript.includes("你没时间了")) {
        window.dispatchEvent(new CustomEvent('voice-action', { detail: "你没时间了" }));
        } 
      };

      // 语音识别结束时的回调
      recognition.current.onend = () => {
        console.log("语音识别已结束");
        setIsListening(false);
      };

      // 语音识别错误时的回调
      recognition.current.onerror = (event: any) => {
        console.error("语音识别错误:", event.error);
      };
    } else {
      console.error("您的浏览器不支持语音识别");
    }
  }, []);

  // 开始语音识别
  const startListening = () => {
    if (recognition.current) {
      recognition.current.start();
      console.log("开始语音识别...");
      setIsListening(true);
    }
  };

  // 停止语音识别
  const stopListening = () => {
    if (recognition.current) {
      recognition.current.stop();
      console.log("停止语音识别");
      setIsListening(false);
    }
  };






  return (
    <div onClick={() => setFlag(!flag)}
      className={isWhite ? 'blue-bottom' : 'white-bottom'}
      style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>

       <img
          onClick={ flag ? startListening:stopListening}

          src={flag ? stopAudioImg:startAudioImg} alt=""
          style={{ width: '150px', height: '150px', borderRadius: '50%', 
            marginBottom: '85px',
            zIndex:5
           }}

        /> 

    </div>
  )
}

export default BottomCom
